package cc.yaomm.common.basic.domain;

import cc.yaomm.common.basic.util.BeanUtils;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;
import ma.glasnost.orika.metadata.TypeBuilder;
import ma.glasnost.orika.metadata.TypeFactory;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Data
public class Paging<T extends Serializable> implements Serializable {

    /**
     * 起始页
     */
    private int page = 1;

    /**
     * 每页条数
     */
    private int size = 10;

    /**
     * 总数
     */
    private int total = 0;

    /**
     * 是否count统计
     */
    private boolean isCount = true;

    /**
     * 排序
     */
    private List<Sort> sort;

    /**
     * 查询参数
     */
    private T condition;

    /**
     * 响应数据
     */
    private List<T> records = Collections.emptyList();

    /**
     * 自定义分页转mybtis分页
     *
     * @return
     */
    public Page<T> toPage() {
        Page<T> page = new Page<>();
        page.setSize(this.size);
        page.setCurrent(this.page);
        page.setSearchCount(this.isCount);
        if (!CollectionUtils.isEmpty(sort)) {
            List<OrderItem> orders = sort.stream().map(x -> {
                OrderItem orderItem = new OrderItem();
                orderItem.setAsc(org.springframework.data.domain.Sort.Direction.ASC.equals(x.getDirection()));
                orderItem.setColumn(x.getProperty());
                return orderItem;
            }).collect(Collectors.toList());
            page.setOrders(orders);
        }
        return page;
    }

    /**
     * mybatis转定义分页
     *
     * @param page
     * @param tClass
     * @param <D>
     * @param <T>
     * @return
     */
    public static <D, T extends Serializable> Paging<T> toPaging(Page<D> page, Class<T> tClass) {
        Paging<T> paging = BeanUtils.getMapper().map(page,
                new TypeBuilder<Page<D>>() {
                }.build(),
                TypeFactory.valueOf(Paging.class, TypeFactory.valueOf(tClass)));
        paging.setPage(Integer.valueOf(page.getCurrent() + ""));
        return paging;
    }

    /**
     * 自定义分页转泛型
     *
     * @param dClass
     * @param <D>
     * @return
     */
    public <D extends Serializable> Paging<D> convert(Class<T> tClass, Class<D> dClass) {
        return BeanUtils.getMapper().map(this,
                TypeFactory.valueOf(Paging.class, TypeFactory.valueOf(tClass)),
                TypeFactory.valueOf(Paging.class, TypeFactory.valueOf(dClass))
        );
    }
}
